package mz.matafe.bolao

import org.codehaus.groovy.grails.plugins.springsecurity.Secured

class MatchController extends BolaoController{

    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    @Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        def matches = Match.list(params)
        def groups = Group.list(params)
        [ groups: groups, matches: matches, matchesCount: Match.count() ]
    }

    @Secured(['ROLE_ADMIN'])
    def create = {
        def match = new Match()
        match.properties = params
        def lastMatchNumber = Match.executeQuery('select max(matchNumber) from Match')
        def lastMatch = Match.find('from Match where id = (select max(id) from Match)')
        if (lastMatch){
            match.matchNumber = lastMatch.matchNumber+1
        }else{
            match.matchNumber = 1
        }
        ['match':match]
    }

    @Secured(['ROLE_ADMIN'])
    def save = {
        def match = new Match(params)
        if(!match.hasErrors() && match.save()) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'match.label', default: 'Match'), match.matchNumber])}"
            redirect(action:show,id:match.id)
        }
        else {
            render(view:'create',model:[match:match])
        }
    }

    @Secured(['ROLE_ADMIN','ROLE_SUPERVISOR'])
    def show = {
        def match = Match.get( params.id )
        if(!match) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'match.label', default: 'Match'), params.id])}"
            redirect(action:list)
        }
        else { 
            [ match : match ]
        }
    }

    @Secured(['ROLE_ADMIN'])
    def delete = {
        def match = Match.get( params.id )
        def matchNumber = match.matchNumber
        if(match) {
            try {
                def bets = Bet.findAllByMatch(match)
                log.debug 'bets....'+bets
                if (!bets.isEmpty()){
                    flash.message = "${message(code: 'match.not.deleted.because.has.bets.message', args: [matchNumber])}"
                    redirect(action:show,id:params.id)
                    //render(view:'show',model:[match:match])
                    return
                }

                match.delete(flush:true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'match.label', default: 'Match'), matchNumber])}"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'match.label', default: 'Match'), matchNumber])}"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'match.label', default: 'Match'), params.id])}"
            redirect(action:list)
        }
    }

    @Secured(['ROLE_ADMIN','ROLE_SUPERVISOR'])
    def edit = {
        def match = Match.get( params.id )
        if(!match) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'match.label', default: 'Match'), params.id])}"
            redirect(action:list)
        }
        else {
            [ match : match ]
        }
    }

    @Secured(['ROLE_ADMIN','ROLE_SUPERVISOR'])
    def update = {
        def match = Match.get( params.id )
        if(match) {
            if(params.version) {
                def version = params.version.toLong()
                if(match.version > version) {
                    match.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'match.label', default: 'Match')] as Object[], "Another user has updated this Match while you were editing")
                    render(view:'edit',model:[match:match])
                    return
                }
            }
            match.properties = params
            if (match.score1 && match.score2)
                match.finished = true
            if(!match.hasErrors() && match.save()) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'match.label', default: 'Match'), match.matchNumber])}"
                redirect(action:show,id:match.id)
            }
            else {
                render(view:'edit',model:[match:match])
            }
        }
        else {
            flash.message = message(code:"match.not.found", args:["${params.id}"])
            redirect(action:list)
        }
    }

    @Secured(['ROLE_ADMIN','ROLE_SUPERVISOR'])
    def editScore = {
        def match = Match.get( params.id )
        if(!match) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'match.label', default: 'Match'), params.id])}"
            redirect(action:list)
        }
        else {
            [ match : match ]
        }
    }

    @Secured(['ROLE_ADMIN','ROLE_SUPERVISOR'])
    def updateScore = {
        def match = Match.get( params.id )
        if(match) {
            if(params.version) {
                def version = params.version.toLong()
                if(match.version > version) {
                    match.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'match.label', default: 'Match')] as Object[], "Another user has updated this Match while you were editing")
                    render(view:'editScore',model:[match:match])
                    return
                }
            }
            match.properties = params
            if (!params.score1) {
                match.errors.rejectValue('result', 'score1.blank')
                render(view:'editScore', model:[match:match])
                return
            }
            if (!params.score2) {
                match.errors.rejectValue('result', 'score2.blank')
                render(view:'editScore', model:[match:match])
                return
            }
            match.finished = true
            if(!match.hasErrors() && match.save()) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'match.label', default: 'Match'), match.matchNumber])}"
                redirect(action:show,id:match.id)
            }
            else {
                render(view:'editScore',model:[match:match])
            }
        }
        else {
            flash.message = message(code:"match.not.found", args:["${params.id}"])
            redirect(action:list)
        }
        }
    }
